package yunplus.io.hchome.presenter.implement;

import android.app.Activity;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import yunplus.io.hchome.display.view.ILaunchView;
import yunplus.io.hchome.model.api.FPM;
import yunplus.io.hchome.model.api.contract.IFPMCallback;
import yunplus.io.hchome.model.storage.DomainShared;
import yunplus.io.hchome.presenter.contract.ILaunchExtPresenter;
import yunplus.io.hchome.presenter.contract.ILaunchPresenter;

/**
 * Created by WangFan on 2017/3/16.
 */

public class LaunchExtPresenter extends LaunchPresenter implements ILaunchExtPresenter {

    private final static String TAG = "LaunchExtPresenter";

    public LaunchExtPresenter(Activity activity, ILaunchView view) {
        super(activity, view);
    }

    @Override
    public void launch() {
        if(DomainShared.isSavedDomain(_mActivity)){
            Log.d(TAG, "start app");
            final String domain = DomainShared.getDomain(_mActivity);
            if(isLan()){
                if(isWifi()){
                    //尝试内网连接
                    _mView.checkNetworkStart();
                    FPM.me().init(ILaunchPresenter.LAN_CGI_URL).ping( new IFPMCallback() {
                        @Override
                        public void onFailure(String code, String message) {
                            //内网无服务，返回登陆
                            _mView.goLoginWithWifi(true);
                        }

                        @Override
                        public void onSuccess(JSONObject result) {
                            _mView.startAppFromLan(domain, true);
                        }
                    });
                    return;
                }else{
                    //上次是内网 &&  本次没有链接wifi，则登陆
                    _mView.goLoginWithWifi(false);
                    return;
                }
            }else{
                //外网，直接打开
                _mView.startAppFromLan(domain, false);
            }
        }else{
            Log.d(TAG, "go login");
            _mView.goLoginWithWifi(isWifi());
        }
    }

    @Override
    public boolean isLan() {
        return "lan".equals(DomainShared.getGatewayType(super._mActivity));
    }
}
